package org.adg.code.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.adg.code.model.DownloadFile;
import org.adg.code.model.NewReportReturn;
import org.adg.code.model.OpenReportList;
import org.adg.code.model.ReportValues;





/**
 * Servlet implementation class MasterServlet
 */
public class MasterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MasterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProcess(request, response);
	}
	 public void doProcess(HttpServletRequest request, HttpServletResponse response)
	 {
		 String method = request.getParameter("method");   
		
		 if(!(method.equalsIgnoreCase("userlogin"))&&!(hasLoggedIn(request, response)))
		 {	 
			 	
				 try {
						response.sendRedirect("index.jsp");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			
		 }
		 else
	
		 if(method.equalsIgnoreCase("userlogin"))         //on submit from login page
		 {
			 Login l=new Login();
			l.userlogin(request,response);
		 }
		else
			if(method.equalsIgnoreCase("mainpage"))       //redirect To main page
			{
				
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/mainpage.jsp");
				try {
					dispatcher.forward(request, response);
					} catch (ServletException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		else
			if(method.equalsIgnoreCase("adduser"))          //on add user click from menu To add user page
			{ 
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/reportuseradd.jsp");
				request.setAttribute("flag", "0");
				try {
					dispatcher.forward(request, response);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		else
			if(method.equalsIgnoreCase("saveuser"))			//on submit from add user to save new user details
			{ 
				
				UserController ua=new UserController();
				if(ua.userNameExists(request.getParameter("username")))
				{
					request.setAttribute("un", request.getParameter("username"));
					request.setAttribute("fn", request.getParameter("fname"));
					request.setAttribute("ln", request.getParameter("lname"));
					request.setAttribute("a1", request.getParameter("add1"));
					request.setAttribute("a2", request.getParameter("add2"));
					request.setAttribute("a3", request.getParameter("add3"));
					request.setAttribute("p", request.getParameter("phno"));
					request.setAttribute("m", request.getParameter("mob"));
					request.setAttribute("ut", request.getParameter("usertitle"));
					request.setAttribute("e", request.getParameter("edu"));
					request.setAttribute("l", request.getParameter("license"));
					request.setAttribute("v", request.getParameter("validupto"));
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/reportuseradd.jsp");
					request.setAttribute("flag", "1");
					try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else
				{	if(ua.saveUser(request,response)){
						displayMsg(request,response,"User Added","adg.do?method=adduser");
					}
					else{
						displayMsg(request,response,"add user failed","adg.do?method=adduser");
						
					}
				}
			}
		else
			if(method.equalsIgnoreCase("edituser"))			//on edit user click from menu to edit user namelist page
			{ 
				UserController ue=new UserController();
				ResultSet rs=ue.getUserList(request,response);
				request.setAttribute("resultset", rs);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/reportuseredit_list.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		else
			if(method.equalsIgnoreCase("edituserdetails"))		//on submit of username selected from the list,to user details edit page
			{ 
				UserController ue=new UserController();
				ResultSet rs=ue.getUserDetails(request,response);
				request.setAttribute("resultset", rs);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/reportuser_modify.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		else
			if(method.equalsIgnoreCase("userupdate"))      //on submit of edited user details
			{ 
				UserController ue=new UserController();
				if(ue.userupdate(request,response))
				{
					displayMsg(request,response,"User Details Updated","adg.do?method=edituser");
				}
				else
				{
					displayMsg(request,response,"User Details Not Updated","adg.do?method=edituser");
				}
			}
		
		else
			if(method.equalsIgnoreCase("deluser")) 			//on del user click from the menu,to username list page
			{ 
				UserController ud=new UserController();
				ResultSet rs=ud.getUserList(request,response);
				request.setAttribute("resultset", rs);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/reportuserdel_list.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		else
			if(method.equalsIgnoreCase("removeuser"))		//on submit of the name selected from list to delete
			{ 
				UserController ud=new UserController();
				if(ud.removeUser(request,response))
				{
					displayMsg(request,response,"User Deleted","adg.do?method=deluser");
				}
			}
		else
			if(method.equalsIgnoreCase("logout"))
			{
				Logout l=new Logout();
				l.userLogout(request,response);
			}
		else
			if(method.equalsIgnoreCase("addtemplate"))		//on addtemplate click from menu,to addtemplate page
			{ 
				TemplateController tc=new TemplateController();
				ArrayList<Object> alobj=tc.getTemplateOtions(request,response);
				ResultSet rs;
				rs=(ResultSet)alobj.get(0);
				request.setAttribute("resultset1", rs);
				rs=(ResultSet)alobj.get(1);
				request.setAttribute("resultset2", rs);
				request.setAttribute("flag","0");
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/addtemplate.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					}
			}
			else
				if(method.equalsIgnoreCase("savetemplate"))			//on submit of addtemplate page
				{ 
					
						TemplateController tc=new TemplateController();
						if(!tc.tempNameExists(request.getParameter("tfname")))
						{
							ArrayList<Object> alobj=tc.getTemplateOtions(request,response);
							ResultSet rs;
							rs=(ResultSet)alobj.get(0);
							request.setAttribute("resultset1", rs);
							rs=(ResultSet)alobj.get(1);
							request.setAttribute("resultset2", rs);
							request.setAttribute("flag","1");
							RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/addtemplate.jsp");
							try {
								dispatcher.forward(request, response);
							} catch (ServletException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
							} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
							}
						}
						else if(tc.repCatExists(request.getParameter("rname")))
						{
							ArrayList<Object> alobj=tc.getTemplateOtions(request,response);
							ResultSet rs;
							rs=(ResultSet)alobj.get(0);
							request.setAttribute("resultset1", rs);
							rs=(ResultSet)alobj.get(1);
							request.setAttribute("resultset2", rs);
							request.setAttribute("flag","2");
							RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/addtemplate.jsp");
							try {
								dispatcher.forward(request, response);
							} catch (ServletException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
							} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
							}
						}
						else
						{	if(tc.saveTemplate(request,response)){
								displayMsg(request,response,"Template Added","adg.do?method=addtemplate");
							}
							else{
								displayMsg(request,response,"Template not Added","adg.do?method=addtemplate");
							}
						}
				}
		else
			if(method.equalsIgnoreCase("newreport"))			//on new report click from the menu,to report catagory list page
			{
				ReportController rc=new ReportController();
				ResultSet rs=rc.getReportCatNames(request,response);
				request.setAttribute("resultset", rs);
				request.setAttribute("flag", "0");
				String s[]={"text","password","textarea"};
				request.setAttribute("str", s);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/newreportnamelist.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
			}
		else
			if(method.equalsIgnoreCase("newreportform"))		//on submit of the selected report category,to new report page
			{
				ReportController rc=new ReportController();
				NewReportReturn nrr=rc.getReportSet(request,response);
				
				request.setAttribute("rn", request.getParameter("rcatname"));
				request.setAttribute("nrr", nrr);
				request.setAttribute("unames",nrr.getUnames());
				
				
				request.setAttribute("f", "0");
				request.setAttribute("flag", "1");
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/newreport.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		else
			if(method.equalsIgnoreCase("savereport"))			//on submit of the new report
			{ 
				ReportController rc=new ReportController();
				if(rc.repNameExists(request.getParameter("rname")))
				{
					NewReportReturn nrr=rc.getReportSet(request,response);
					
					request.setAttribute("rn", request.getParameter("rname"));
					request.setAttribute("nrr", nrr);
					request.setAttribute("unames",nrr.getUnames());
					
					
					request.setAttribute("f", "1");
					request.setAttribute("flag", "1");
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/newreport.jsp");
					try {
							dispatcher.forward(request, response);
						} catch (ServletException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
						} catch (IOException e) {
								// TODO Auto-generated catch block
							e.printStackTrace();
						}
				}
				else
				{	if(rc.saveReport(request,response)){
						displayMsg(request,response,"Report Added","adg.do?method=newreport");
					}
					else{
						displayMsg(request,response,"Report not Added","adg.do?method=newreport");
					}
				}
					
			}
		else
			if(method.equalsIgnoreCase("openreport"))			//on open report click from menu,to report category name list
			{ 
				ReportController rc=new ReportController();
				ResultSet rs=rc.getReportCatNames(request,response);
				request.setAttribute("resultset", rs);
				request.setAttribute("flag", "0");
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/openreportnamelist.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		else
			if(method.equalsIgnoreCase("openreportlist"))		//on submit of selected report category name,to report name list page
			{ 
				
				ReportController rc=new ReportController();
				ResultSet rs=rc.getReportCatNames(request,response);
				request.setAttribute("resultset", rs);
				ArrayList<String> al=rc.getReportNames(request,response);
				OpenReportList or=new OpenReportList();
				or.setList(al);
				request.setAttribute("repcat",request.getParameter("rname"));
				request.setAttribute("rlist", or);
				request.setAttribute("flag", "1");
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/openreportnamelist.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
				
			}
		else
			if(method.equalsIgnoreCase("showreport"))		//on submit of selected report name,to show report page
			{ 
				ReportController rc=new ReportController();
				NewReportReturn nrr=rc.openReportSet(request,response);
				ReportValues rs=rc.openReportValues(request,response);
				request.setAttribute("rn", request.getParameter("catgname"));
				request.setAttribute("nrr", nrr);
				request.setAttribute("unames",nrr.getUnames());
				request.setAttribute("datavalues", rs);
				
		
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/openreport.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
						
			}
		else
			if(method.equalsIgnoreCase("updatereport"))			//on submit of edited report details
			{
				ReportController rc=new ReportController();
				if(rc.updateReport(request,response)){
					displayMsg(request,response,"Report Updated","adg.do?method=openreport");
				}
				else{
					displayMsg(request,response,"Report not Updated","adg.do?method=openreport");
				}
			}
		 
		
		else
			if(method.equalsIgnoreCase("removereport"))			//on submit of report name selected to delete
			{ 
				ReportController rc=new ReportController();
				rc.removeReport(request,response);
							
			}
		else
			if(method.equalsIgnoreCase("generatereport"))		//on generate report click from the menu,report category name list
			{ 
				ReportController rc=new ReportController();
				ResultSet rs=rc.getReportCatNames(request,response);
				request.setAttribute("resultset", rs);
				
				request.setAttribute("flag", "0");
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/generatereportnamelist.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
								
			}
		else
			if(method.equalsIgnoreCase("generatereportlist"))		//on submit of selected report category,to report name list
			{ 
					
				ReportController rc=new ReportController();
				ResultSet rs=rc.getReportCatNames(request,response);
				request.setAttribute("resultset", rs);
				ArrayList<String> al=rc.getReportNames(request,response);
				OpenReportList or=new OpenReportList();
				or.setList(al);
				request.setAttribute("repcat",request.getParameter("rname"));
				request.setAttribute("rlist", or);
				request.setAttribute("flag", "1");
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/generatereportnamelist.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
			}
		else
			if(method.equalsIgnoreCase("showreportTogen"))		//on submit of report name selected,to show the report details
			{ 
				ReportController rc=new ReportController();
				NewReportReturn nrr=rc.openReportSet(request,response);
				ReportValues rs=rc.openReportValues(request,response);
				request.setAttribute("rn", request.getParameter("catgname"));
				request.setAttribute("nrr", nrr);
				request.setAttribute("unames",nrr.getUnames());
				request.setAttribute("datavalues", rs);
				
		
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/generatereport.jsp");
				try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
					} catch (IOException e) {
							// TODO Auto-generated catch block
						e.printStackTrace();
					}
						
			}
		else
			if(method.equalsIgnoreCase("generatereportfile"))	//on submit of report name selected to generate
			{ 
				ReportController rc=new ReportController();
				if(rc.generateReport(request,response))
				{
					displayMsg(request,response,"Report Generated","adg.do?method=generatereport");
				}
				else
				{
					displayMsg(request,response,"Report Generated","adg.do?method=generatereport");
				}
				
			}
		else
			if(method.equalsIgnoreCase("downloadreportfile"))	//on submit of report name selected to download
			{ 
				try
				{
					ReportController rc=new ReportController();
				
				 // set the http content type to "APPLICATION/OCTET-STREAM
				  

				   // initialize the http content-disposition header to
				   // indicate a file attachment with the default filename
				   // "myFile.txt"
					String rname=(String)request.getParameter("reportname");
				   DownloadFile df=rc.getDownloadFile(rname);
				   response.setContentType("APPLICATION/TEXT");
				   String fnm=df.getFilename().replaceAll(" ","-");
				   response.setHeader("Content-Disposition", "attachment; filename=" +fnm);
				   PrintWriter out = response.getWriter();
				   // transfer the file byte-by-byte to the response object
				   
				   FileInputStream fileInputStream = df.getF();
				   int i;
				   while ((i=fileInputStream.read())!=-1)
				   {
				      out.write(i);
				   }
				   fileInputStream.close();
				   out.close();
				}
				
			 catch (IOException e) {
					// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	 }
	 public boolean hasLoggedIn(HttpServletRequest request, HttpServletResponse response)
	 {
		 HttpSession session = request.getSession();
		 String uname = (String)session.getAttribute("uname"); 
		
	  		if (uname == null)
	  		{
	  				return false;
	  		}
	  		return true;
	}
	 public void displayMsg(HttpServletRequest request, HttpServletResponse response,String msg,String act)
	 {
		 try {
			response.setContentType("text/html");
		
         PrintWriter pw = response.getWriter();
		
         pw.print("<html>");
         pw.print("<head>");
         pw.print("<Script Language=\"JavaScript\">");
         pw.print("function disp(){");
         pw.print("alert(\""+msg+"\");");
         pw.print("document.getElementById(\"form2\").action=\""+act+"\";");
         pw.print("document.getElementById(\"form2\").submit();}");
         pw.print("</Script>");
         pw.print("</head>");
         pw.print("<body onload=\"disp()\">");
         pw.print("<form id=\"form2\"  name=\"form2\" method=\"post\" action=\"\">");
         pw.print("</form>");
         pw.print("</body>");
         pw.print("</html>");
		 } catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	 }
}
